<template>
  <div id="app">
    <NavigationBar v-if="oauth" />
    <router-view v-if="oauth" class="router" />
  </div>
</template>
<script>
// @ is an alias to /src
import NavigationBar from '@/components/NavigationBar/index.vue'


//防止样式反复计算从而死循环
const debounce = (fn, delay) => {
  let timer = null;

  return function () {
    let context = this;

    let args = arguments;

    clearTimeout(timer);

    timer = setTimeout(function () {
      fn.apply(context, args);
    }, delay);
  };
};

// 解决ERROR ResizeObserver loop completed with undelivered notifications.
const _ResizeObserver = window.ResizeObserver;

window.ResizeObserver = class ResizeObserver extends _ResizeObserver {
  constructor(callback) {
    callback = debounce(callback, 16);
    super(callback);
  }
};
export default {
  name: 'HomeView',
  data() {
    return {
      id: '0',
      oauth: false,
      hideNavigationBar: false,
    }
  },
  components: {
    NavigationBar
  },
  created() {
    this.beforeMount();
  },
  methods: {
    async beforeMount() {
      const route = this.$route;
      const router = this.$router;

      await router.isReady();

      let authCode = route.query.code;

      if (authCode) {
        this.$Request.get(this.$urlApi.login.token, {
          code: authCode,
          grant_type: 'authorization_code',
          redirect_uri: location.origin,
        }).then(res => {
          if (res.data.code == 200) {
            localStorage.setItem('TOKENDATA', JSON.stringify(res.data.data));
            location.replace(location.origin);
          }
        }).catch(res => {
          // handle error
        });
      } else {
        this.$Request.get(this.$urlApi.login.userinfo).then(res => {
          if (res.data.code == 200) {
            localStorage.setItem('USERINFO', JSON.stringify(res.data.data));
            this.oauth = true;
          } else {
            localStorage.clear();
            location.replace(location.origin);
          }
        }).catch(res => {
          // handle error
        });
      }
    }
  }
}
</script>


<style lang="scss"></style>
